package server;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;

import org.omg.CORBA.portable.ApplicationException;

import dataContracts.Command;
import dataContracts.SharedFile;

class SendFileHandler implements Runnable {
	ClientConnection client;
	ServerProgram server;
	String fileName;
	long timestamp;
//	String directoryPath;
	// HACK: 0 means download, 1 means upload
	public short operation = 0;
	Command command;
	
	SendFileHandler(ClientConnection client, ServerProgram server, Command cmd, String fileName) {
		this.server = server;
		this.client = client;
		this.fileName = fileName;
		this.command = cmd;
		timestamp = new Date().getTime();
//		this.directoryPath = directoryPath; 
	}
	
	@Override
	public void run() {
		DownloadServer ds = null;
		
		if (command.directoryInfo != null) {
			// default timestamp to now, for if we can find it
			SharedFile sf = command.directoryInfo.findFile(fileName);
			if (sf != null) {
				timestamp = sf.lastModified;
			} else {
				util.Logger.Debug("Couldn't find file for timestamping - "+ fileName);
			}
		}
		
		try {
			ds = setupServerOnOpenPort();
			// send back the filename and port so the client can download
			if (operation == 0) {
				client.command(Command.Type.RecvFile, fileName + ":" + ds.port);
			} else {
//				try {
//					server.directory.addFile(fileName);
//				} catch (FileNotFoundException e) {
//					e.printStackTrace();
//				}
				server.commandAllClients(new Command(Command.Type.GetFile, fileName + ":" + ds.port));
			}
			
			// send the download to the client
			ds.run();
		} catch (ApplicationException ex) {
			// notify the client that it needs to try again later...
			client.notify("There are too many clients downloading, try again shortly...");
		}
	}
	
	private DownloadServer setupServerOnOpenPort() throws ApplicationException {
		//start with the server port and move up
		int port = server.portNumber+1, maxClients = 1000;
		DownloadServer ds;
		
		while (port < server.portNumber + maxClients) {
			try {
				ds = new DownloadServer(fileName, timestamp, port, server.directory);
				// if no exception was thrown, the port is available
				ds.operation = operation;
				return ds;
			} catch (IOException e) {
				// couldn't connect, try the next port
				port++;
			}
		}
		
		// if we get here, it means we could not find an open port... 
		throw new ApplicationException("There are too many clients downloading, try again shortly...", null);
	}
}